//跨越访问直接调用api 第一个demo版本
//非常强烈建议不要这样去写 
//稍微会点的人会完全利用BUG去疯狂提交
//此方法理论上没有任何的安全性可言
//随便都能攻破
//纯属本人随便搞着玩的。
//这种写法一般人会写代码的人看了会吐血

//开始写了 2018-07-23 10:52 
var API = {
	key:"yttrium"
};
//API调用的跨域URL
API.Url= {
	add: 'https://wx.yttrium2016.cn/cors/my-add',
	find: "https://wx.yttrium2016.cn/cors/my-find",
	size: "https://wx.yttrium2016.cn/cors/my-size",
	edit: "https://wx.yttrium2016.cn/cors/my-edit",
	delete: "https://wx.yttrium2016.cn/cors/my-delete"
};
//获取sessionStorage值 ,没有 默认为 ''
API.getStorage = function(k){
	if (!!window.sessionStorage[API.key]) {
		return JSON.parse(window.sessionStorage.getItem(API.key))[k];
	}else{
		return "";
	}
}
//显示加载(需导入<script src="js/jquery-weui.js"></script>)
API.showLoading = function(msg){
	$.showLoading(!!msg?msg:'加载中...');
}
//隐藏加载(需导入<script src="js/jquery-weui.js"></script>)
API.hideLoading = function(){
	$.hideLoading();
}
//保存一个K,V
API.putStorage = function(k,v){
	if (!window.sessionStorage[API.key]) {
		var obj = {};
		obj[k] = v;
		window.sessionStorage[API.key] = JSON.stringify(obj);
	}else{
		var obj = JSON.parse(window.sessionStorage[API.key]);
		obj[k] = v;
		window.sessionStorage[API.key] = JSON.stringify(obj);
	}
}
//删除一个K,V 为空就是全删除
API.removeStorage = function(k){
	if(!k)
		window.sessionStorage.removeItem(API.key);
	else{
		var obj = JSON.parse(window.sessionStorage[API.key]);
		obj[k] = '';
		window.sessionStorage[API.key] = JSON.stringify(obj);
	} 	
}
//获取错误信息
API.getResult = function(msg,code,data){
	var obj = {};
	obj.code = code == null ? -1 : code;
	obj.msg = msg;
	obj.data = data == 'undefined' ? null : data;
	return obj;
}
//登录
API.login = function(username,password,cb){
	var querydata = {"andWhere": [{ "key": "username", "type": "EQ", "value": username },{ "key": "password","type": "EQ", "value": password }],"tableName":"user"}
	$.ajax({
	    type: "post",
        url: this.Url.find,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(data.code == 0 && data.data.length == 1){
        		//登录成功浏览器记录下用户ID
        		API.putStorage("user",data.data[0].user_id);
        		//记录下用户的注册时间
        		API.putStorage("date",data.data[0].create_date.substring(0,10).replace('-','年').replace('-','月')+'日');
        	}
        	if(typeof cb == "function"){
        		cb(data,textStatus);
        	}else{
        		console.log(data,'API.login');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
}
//注册
API.register = function(username,password,name,cb){
	var querydata = {"andWhere": [{ "key": "username", "type": "EQ", "value": username }],"tableName":"user"}
	//看用户名是否重复
	$.ajax({
	    type: "post",
//      async: false,
        url: this.Url.size,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(data.code == 0 && data.data == 0){
        		//注册操作
		    	var addData = {"data":{"username":username,"name":name,"password":password},"tableName":"user"}
		    	$.ajax({
				    type: "post",
//			        async: false,
			        url: API.Url.add,
			        dataType: "json",
			        data: {
			            "data": JSON.stringify(addData)
			        },
			        success: function (data, textStatus) {
			    		if(typeof cb == "function"){
			        		cb(data,textStatus);
			        	}
			        },
			        error: function () {
			        	console.log('API.login error');
			    	}
			    });
        	}else{
        		if(typeof cb == "function"){
	        		cb(API.getResult('此用户名已存在'),textStatus);
	        	}
        	}
        	
        }
        , error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
    
}
//主页获取数据
API.getIndexData = function(userId){
	var result = {};
	
	var querydata = {"andWhere": [{ "key": "user", "type": "EQ", "value": ""+userId+"" }],"tableName":"item","order":"date_time"}
	$.ajax({
	    type: "post",
        url: this.Url.find,
        async: false,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(data.code == 0){
        		result.list = data.data;
        	}else{
        		console.log(data,'API.getIndexData success');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
    
    result.itemList = [];
    result.mIn = 0;
    result.mOut = 0;
    if(result.list != null && result.list.length > 0){
    	var m,y,d,mIn = 0,mOut = 0,itemdata;
    	for(var i = 0;i<result.list.length;i++){
    		var item = result.list[i];
    		var obj = {};
    		if(item.type == 0){
				result.mIn += item.money;
			}
			if(item.type == 1){
				result.mOut += item.money;
			}
    		obj.id = item.item_id;
			obj.color = item.color;
			obj.icon = item.icon;
			obj.money = item.money;
			obj.title = item.title;
			obj.type = 0;//默认一条
			obj.old = item.type;
			if(i == 0){
				m = item.month;
				y = item.year;
				d = item.day;
				itemdata = item.data_num.substr(0,8);
			}
			
			if(itemdata == item.data_num.substr(0,8)){
				if(item.type == 0){
					mIn += item.money;
				}
				if(item.type == 1){
					mOut += item.money;
				}
			}else{
				if(mOut != 0 || mIn != 0){
					var obj1 = {};
					obj1.type = 1;
					obj1.day = d;
					obj1.mIn = mIn;
					obj1.mOut = mOut;
					result.itemList.push(obj1);
				}
				
				if(m != item.month){
					var obj2 = {};
					obj2.type = 2;
					obj2.month = m;
					result.itemList.push(obj2);
				}
				
				m = item.month;
				y = item.year;
				d = item.day;
				itemdata = item.data_num.substr(0,8);
				if(item.type == 0){
					mIn = item.money;
				}else{
					mIn = 0;
				}
				if(item.type == 1){
					mOut = item.money;
				}else{
					mOut = 0;
				}
				
			}
			
			result.itemList.push(obj);
			
			if(i == result.list.length-1){
				var obj3 = {};
				obj3.type = 1;
				obj3.day = d;
				obj3.mIn = mIn;
				obj3.mOut = mOut;
				result.itemList.push(obj3);
				m = item.month;
				y = item.year;
				d = item.day;
				mOut = 0;
				mIn = 0;
			}
			
		}
    }
    
    result.sum = (result.mIn - result.mOut);
    
    return result;
}
//添加一条记录
API.addItem = function(item,cb){
	var addData = {
		"data":item,
		"tableName":"item"
	}
	if(typeof cb == "function"){
		$.ajax({
		    type: "post",
	        async: false,
	        url: this.Url.add,
	        dataType: "json",
	        data: {
	            "data": JSON.stringify(addData)
	        },
	        success: function (data, textStatus) {
	        	if(typeof cb == "function"){
	        		cb(data,textStatus);
		        }
	        }, 
	        error: function () {
	        	if(typeof cb == "function"){
	        		cb(API.getResult('网络出错'));
		        }
	    	}
	    });
	}else{
		var result = false;
		$.ajax({
		    type: "post",
	        async: false,
	        url: this.Url.add,
	        dataType: "json",
	        data: {
	            "data": JSON.stringify(addData)
	        },
	        success: function (data, textStatus) {
	    		if(data.data > 0){
	    			result = true;
	    		}
	        }, 
	        error: function () {
	        	console.log('API.addTag error');
	    	}
	    });
	    return result;
	}
}
//获取一条记录通过ID
API.getItemById = function(id,cb){
	var querydata = {"andWhere":[{"key":"item_id","type":"EQ","value":""+ id +""}],"tableName":"item"}
	$.ajax({
	    type: "post",
        url: this.Url.find,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
        	}else{
        		console.log(data,'API.getTag success');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
}

//添加一个标签
API.addTag = function(tag,cb){
	var addData = {
		"data":tag,
		"tableName":"tag"
	}
	if(typeof cb == "function"){
		$.ajax({
		    type: "post",
	        url: this.Url.add,
	        dataType: "json",
	        data: {
	            "data": JSON.stringify(addData)
	        },
	        success: function (data, textStatus) {
	        	if(typeof cb == "function"){
	        		cb(data,textStatus);
		        }
	        }, 
	        error: function () {
	        	if(typeof cb == "function"){
	        		cb(API.getResult('网络出错'));
		        }
	    	}
	    });
	}else{
		var result = false;
		$.ajax({
		    type: "post",
	        async: false,
	        url: this.Url.add,
	        dataType: "json",
	        data: {
	            "data": JSON.stringify(addData)
	        },
	        success: function (data, textStatus) {
	    		if(data.data > 0){
	    			result = true;
	    		}
	        }, 
	        error: function () {
	        	console.log('API.addTag error');
	    	}
	    });
	    
	    return result;
	}
}
//获取标签
API.getTag = function(userId,cb){
	var querydata = {"andWhere":[{"key":"user","type":"EQ","value":""+ userId +""}],"tableName":"tag"}
	$.ajax({
	    type: "post",
        url: this.Url.find,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
        	}else{
        		console.log(data,'API.getTag success');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
}
//获取一个TAG通过ID
API.getTagById = function(id,cb){
	var querydata = {"andWhere":[{"key":"tag_id","type":"EQ","value":""+ id +""}],"tableName":"tag"}
	$.ajax({
	    type: "post",
        url: this.Url.find,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
        	}else{
        		console.log(data,'API.getTagById success');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
}

API.updateTagById = function(tag,id,cb){
	var editdata = {"data":tag,"id":id,"tableName":"tag"};
	$.ajax({
	    type: "post",
        url: this.Url.edit,
        dataType: "json",
        data: {
            "data": JSON.stringify(editdata)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
        	}else{
        		console.log(data,'API.updateTagById success');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
}

//添加默认标签
API.initTag = function(userId,cb){
	//收入
	var a = ['工资','生活费','红包','零花钱','外快兼职','投资收入','奖金','报销','现金','退款','其他'];
	var b = ['#6B86BD','#DEBE63','#FF969C','#8C9273','#63B2C6','#D66908','#F7964A','#B5DBD6','#9CDFBD','#BD757B','#9CDFFF'];
	var c = ['#icon-mianbao2','#icon-mianbao1','#icon-shutiao','#icon-tiantianquan','#icon-pisa','#icon-mianbao','#icon-yinl','#icon-yinliao7','#icon-yinliao6','#icon-bingjiling','#icon-yinliao4'];
	var num = 0;
	for(var i = 0;i<a.length;i++){
		var obj = {};
		//数据库建错了 记得修复
		obj.icon = c[i];
		obj.title = a[i];
		obj.type = 0;
		obj.user = userId;
		obj.color = b[i];
		if(this.addTag(obj)) num++;
	}
	console.log('用户'+userId+'初始化标签tag收入'+num+"个");
	
	//支出
	var x = ['餐饮','交通','酒水饮料','水果','零食',
			 '买菜','鞋包衣服','生活用品','话费','护肤彩妆',
			 '房租','电影','淘宝','红包','药品'];
	var y = ['#FFCB84','#ADBAFF','#9CCBFF','#F7DB6B','#FFBA8C',
			 '#9CDFD6','#CEAEFF','#C6BEEF','#8CC7F7','#F7AAD6',
			 '#94BEE7','#A5E3E7','#FFCB73','#FF969C','#A5D7AD'];
	var z = ['#icon-ziyuan19','#icon-ziyuan15','#icon-ziyuan14','#icon-ziyuan13','#icon-ziyuan12',
			 '#icon-ziyuan10','#icon-ziyuan9','#icon-ziyuan7','#icon-ziyuan6','#icon-ziyuan5',
			 '#icon-ziyuan4','#icon-ziyuan3','#icon-ziyuan2','#icon-ziyuan1','#icon-ziyuan'];
	num = 0;
	for(var i = 0;i<x.length;i++){
		var obj = {};
		//数据库建错了 记得修复
		obj.icon = z[i];
		obj.title = x[i];
		obj.type = 1;
		obj.user = userId;
		obj.color = y[i];
		if(this.addTag(obj)) num++;
	}
	console.log('用户'+userId+'初始化标签tag支出'+num+"个");
	if(typeof cb == "function"){
		cb();
	}
}
//添加数据(通用接口 建议不用)
API.addData = function(tableName,data,cb){
	var addData = {
		"data":data,
		"tableName":tableName
	}
	var result = false;
	$.ajax({
	    type: "post",
        url: this.Url.add,
        dataType: "json",
        data: {
            "data": JSON.stringify(addData)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
	        }
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('添加'+ tableName +'数据出错'));
	        }
    	}
   });
}
//添加图标 随导入js更改 用于自己的提交
API.addIcon = function(icon,cb){
	var addData = {
		"data":{
			"icon":icon
		},
		"tableName":"icon"
	}
	var result = false;
	$.ajax({
	    type: "post",
        url: this.Url.add,
        dataType: "json",
        data: {
            "data": JSON.stringify(addData)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
	        }
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('添加'+ tableName +'数据出错'));
	        }
    	}
   });
}
//添加颜色 可以自己增加
API.addColor = function(color,cb){
	var addData = {
		"data":{
			"color":color
		},
		"tableName":"color"
	}
	var result = false;
	$.ajax({
	    type: "post",
        url: this.Url.add,
        dataType: "json",
        data: {
            "data": JSON.stringify(addData)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
	        }
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('添加'+ tableName +'数据出错'));
	        }
    	}
   });
}
//获取所有图标样式
API.getIcon = function(cb){
	var querydata = {"tableName":"icon"}
	$.ajax({
	    type: "post",
        url: this.Url.find,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
        	}else{
        		console.log(data,'API.getIcon success');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
}
//获取所有颜色样式
API.getColor = function(cb){
	var querydata = {"tableName":"color"}
	$.ajax({
	    type: "post",
        url: this.Url.find,
        dataType: "json",
        data: {
            "data": JSON.stringify(querydata)
        },
        success: function (data, textStatus) {
        	if(typeof cb == "function"){
        		cb(data,textStatus);
        	}else{
        		console.log(data,'API.getIcon success');
        	}
        }, 
        error: function () {
        	if(typeof cb == "function"){
        		cb(API.getResult('网络出错'));
	        }
    	}
    });
}
